package com.yingpai.fitness.dvp_2_0.main.activity;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.lzy.okserver.task.XExecutor;
import com.orhanobut.logger.Logger;
import com.tbruyelle.rxpermissions2.Permission;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.bean.SplashBean;
import com.yingpai.fitness.dvp_2_0.main.bean.VersionBean;
import com.yingpai.fitness.dvp_2_0.main.util.DialogUtil;
import com.yingpai.fitness.dvp_2_0.main.util.XCountDownTimer;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.dvp_2_0.main.widget.CBProgressBar;
import com.yingpai.fitness.entity.wx.TokenBean;

import java.io.File;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * 开屏页
 * Created by ASUS on 2018/11/2.
 */

public class SplashActivity extends CommonActivity implements XExecutor.OnAllTaskEndListener {


    @BindView(R.id.splash_bg)
    ImageView splashBg;
    @BindView(R.id.splash_bottom)
    ImageView splashBottom;
    @BindView(R.id.welcome_banner_count_down_tv)
    TextView welcomeBannerCountDownTv;
    private XCountDownTimer timer;
    private TokenBean tokenBean;
    private OkDownload okDownload;
    private List<DownloadTask> values;
    private DownloadTask task;
    private File file = new File(Environment.getExternalStorageDirectory() +
            File.separator + "yingpai_apk" + File.separator +
            Url.APK_DOWNLOAD.substring(Url.APK_DOWNLOAD.lastIndexOf("/")));

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finishActivity();
            return;
        }
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_welcome_layout);
    }

    private void judgeVersion() {
        obtainJurisdiction();
        finalOkGo.request(RequestType.GET, Contacts.HOST_SERVER + Url.GET_VERSION_INFO,
                null, Url.GET_VERSION_INFO, new Callback<VersionBean>() {
                    @Override
                    public void onSuccess(final VersionBean versionBean) {
                        if (versionBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                            if (getAppVersionCode() < Integer.parseInt(versionBean.getData().getAndroid())) {
                                DialogUtil.getInstance().showCenterDialog(context, R.layout.dialog_shop_pay_success);
                                final View dialog_version = DialogUtil.getInstance().dialog_center_layout;
                                DialogUtil.getInstance().dialog_center.setCanceledOnTouchOutside(false);
                                DialogUtil.getInstance().dialog_center.setCancelable(false);
                                dialog_version.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        DialogUtil.getInstance().dialog_center.dismiss();
                                        countDownTime();
                                    }
                                });
                                final CBProgressBar progressBar = dialog_version.findViewById(R.id.progressBar);
                                dialog_version.findViewById(R.id.sure_cancel).setVisibility(View.VISIBLE);
                                final TextView title = dialog_version.findViewById(R.id.title);
                                title.setText("版本更新");
                                TextView message = dialog_version.findViewById(R.id.message);
                                message.setVisibility(View.GONE);
                                TextView message1 = dialog_version.findViewById(R.id.message1);
                                message1.setText(versionBean.getData().getDesc());
                                final TextView sure = dialog_version.findViewById(R.id.sure);
                                TextView cancel = dialog_version.findViewById(R.id.cancel);
                                View line = dialog_version.findViewById(R.id.line);
                                if (!versionBean.getData().getForceUpdate().equals(Constant.REQUEST_SUCCESS_0)) {
                                    cancel.setVisibility(View.GONE);
                                    line.setVisibility(View.GONE);
                                    dialog_version.findViewById(R.id.close).setVisibility(View.INVISIBLE);
                                }
                                sure.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        //判断是否存储了下载标识并且是否存在下载的文件

                                        Logger.e("name",file.getAbsolutePath());
                                        if (OkDownload.getInstance().hasTask(versionBean.getData().getAndroid())
                                                && file.exists()) {
                                            //存在我们就获取任务继续下载
                                            task = okDownload.getInstance().getTask(versionBean.getData().getAndroid()).
                                                    fileName(Url.APK_DOWNLOAD.substring(Url.APK_DOWNLOAD.lastIndexOf("/")));
                                        } else {
                                            //不存在就移除任务 创建新任务重新下载
                                            OkDownload.getInstance().removeTask(versionBean.getData().getAndroid());

                                            GetRequest<File> request = OkGo.<File>get(Url.APK_DOWNLOAD);
                                            task = OkDownload.request(versionBean.getData().getAndroid(), request).fileName(Url.APK_DOWNLOAD.substring(Url.APK_DOWNLOAD.lastIndexOf("/"))).save();
                                        }

                                        task.register(new DownloadListener(versionBean.getData().getAndroid()) {
                                            @Override
                                            public void onStart(Progress progress) {
                                                title.setText("正在下载");
                                                dialog_version.findViewById(R.id.sure_cancel).setVisibility(View.GONE);
                                                progressBar.setVisibility(View.VISIBLE);
                                                dialog_version.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {
                                                        showToast("正在下载，不能关闭！");
                                                    }
                                                });
                                            }

                                            @Override
                                            public void onProgress(final Progress progress) {
                                                progressBar.setMax(progress.totalSize);
                                                progressBar.setProgress(progress.currentSize);
                                            }

                                            @Override
                                            public void onError(Progress progress) {
                                                Throwable throwable = progress.exception;
                                                if (throwable != null) {
                                                    if (throwable instanceof SocketException) {
                                                        showToast("网络开小差了...");
                                                        cancleDownload(throwable);
                                                    } else if (throwable instanceof UnknownHostException) {
                                                        showToast("无网络");
                                                        cancleDownload(throwable);
                                                    }
                                                    /*else if(throwable instanceof FileNotFoundException){
                                                        rxPermissions.requestEach(
                                                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                                                        ).subscribe(new Consumer<Permission>() {
                                                            @Override
                                                            public void accept(Permission permission) throws Exception {
                                                                if (permission.granted) {
                                                                    // 用户已经同意该权限
                                                                    task = okDownload.getInstance().getTask(versionBean.getData().getAndroid()).
                                                                            fileName(Url.APK_DOWNLOAD.substring(Url.APK_DOWNLOAD.lastIndexOf("/")));
                                                                } else if (permission.shouldShowRequestPermissionRationale) {
                                                                    // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                                                                    showToast("拒绝权限可能导致无法安装最新版程序");
                                                                } else {
                                                                    // 用户拒绝了该权限，并且选中『不再询问』
                                                                    showToast("拒绝权限可能导致无法安装最新版程序");
                                                                }
                                                            }
                                                        });
                                                    }*/
                                                    else {
                                                        OkDownload.getInstance().removeTask(versionBean.getData().getAndroid());
                                                        cancleDownload(throwable);
                                                    }
                                                }
                                            }

                                            @Override
                                            public void onFinish(File file, Progress progress) {
                                                OkDownload.getInstance().removeTask(versionBean.getData().getAndroid());
                                                task.unRegister(this);
                                                DialogUtil.getInstance().dialog_center.dismiss();
                                                installApk(file);
                                            }

                                            @Override
                                            public void onRemove(Progress progress) {

                                            }
                                        });
                                        task.save();
                                        task.start();
                                    }
                                });

                                cancel.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        DialogUtil.getInstance().dialog_center.dismiss();
                                        countDownTime();
                                    }
                                });

                            } else {
                                countDownTime();
                            }
                        } else {
                            showToast(versionBean.getMessage() + "");
                            countDownTime();
                        }
                    }
                });
    }

    /**
     * 判断其它权限
     */
    private void obtainJurisdiction() {
        rxPermissions.requestEach(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.CAMERA
        ).subscribe(new Consumer<Permission>() {
            @Override
            public void accept(Permission permission) throws Exception {
                if (permission.granted) {
                    // 用户已经同意该权限
                } else if (permission.shouldShowRequestPermissionRationale) {
                    // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                    showToast("拒绝权限可能导致部分功能不能使用");
                } else {
                    // 用户拒绝了该权限，并且选中『不再询问』
                    showToast("拒绝权限可能导致部分功能不能使用，如果需要请在设置中修改");
                }
            }
        });
    }

    private void cancleDownload(Throwable throwable) {
        try{
            DialogUtil.getInstance().dialog_center.dismiss();
            showToast("下载失败，可能导致应用不能使用，请尽快更新");
            countDownTime();
            throwable.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private void requestData() {
        Glide.with(getApplicationContext())
                .load("http://download.yingpaitch.com/loading.jpg?" + System.currentTimeMillis())
                .into(splashBg);
        Glide.with(getApplicationContext())
                .load("http://download.yingpaitch.com/loading-logo.png?" + System.currentTimeMillis())
                .into(splashBottom);
        finalOkGo.request(RequestType.GET, Contacts.HOST_SERVER + Url.SPLASH_DATA, null, Url.SPLASH_DATA, new Callback<SplashBean>() {
            @Override
            public void onSuccess(final SplashBean splashBean) {
                if(splashBean.getCode().equals(Constant.REQUEST_SUCCESS_0)){
                    splashBg.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (timer != null) {
                                timer.cancel();
                            }
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("splash",splashBean);
                            startFinishActivity(WebViewActivity.class,bundle);
                        }
                    });
                }
            }
        });

    }

    private void countDownTime() {
        welcomeBannerCountDownTv.setVisibility(View.VISIBLE);
        timer = new XCountDownTimer(6 * 1000, 1000, welcomeBannerCountDownTv, 0);
        timer.start();
        timer.setListener(new XCountDownTimer.OnCountDownNumListener() {
            @Override
            public void setCountDownNum(int num) {
                if (num == 0) {
                    toNextActivity();
                }
            }
        });
    }

    private void requestPermissions() {
        /**
         * 小米手机9.0系统，READ_SYNC_SETTINGS这个权限总是申请不到，百度查了是，获取同步设置
         * 但是权限弹出框是4个，用户全授予了权限，还是提示（用户拒绝了该权限），
         * 先去掉这个权限
         * //Manifest.permission.READ_SYNC_SETTINGS,
         *                 Manifest.permission.WRITE_EXTERNAL_STORAGE,
         *                 Manifest.permission.READ_PHONE_STATE
         *
         *                 new Consumer<Permission>() {
         *             @Override
         *             public void accept(Permission permission) throws Exception {
         *                 if (permission.granted) {
         *                     // 用户已经同意该权限
         *                     judgeVersion();
         *                 } else if (permission.shouldShowRequestPermissionRationale) {
         *                     // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
         *                     showToast("拒绝权限可能导致部分功能不能使用");
         *                 } else {
         *                     // 用户拒绝了该权限，并且选中『不再询问』
         *                     showToast("拒绝权限可能导致部分功能不能使用，如果需要请在设置中修改");
         *                 }
         *             }
         *         }
         */
        rxPermissions.request(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if(aBoolean){
                    judgeVersion();
                }else{
                    showToast("拒绝此权限可能导致无法安装新版本");
                    countDownTime();
                }
            }
        });
    }

    /**
     * 跳转下一个页面
     */
    private void toNextActivity() {
        if (timer != null) {
            timer.cancel();
        }
        if (tokenBean == null || TextUtils.isEmpty(tokenBean.getRegisterId())) {
            startFinishActivity(LoginAndRegisterActivity.class);
        } else {
            startFinishActivity(HomeActivity.class);
        }
    }

    @Override
    @OnClick({R.id.welcome_banner_count_down_tv})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.welcome_banner_count_down_tv:
                toNextActivity();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
        if (okDownload != null) {
            okDownload.removeOnAllTaskEndListener(this);
        }
    }

    @Override
    protected void initView() {
        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);

        okDownload = OkDownload.getInstance();
        okDownload.setFolder(Environment.getExternalStorageDirectory() + File.separator + "yingpai_apk");
        okDownload.getThreadPool().setCorePoolSize(3);
        okDownload.addOnAllTaskEndListener(this);
        values = OkDownload.restore(DownloadManager.getInstance().getDownloading());
    }

    @Override
    protected void initData() {
        requestData();
        requestPermissions();

    }

    @Override
    public void onAllTaskEnd() {
        showToast("下载完成");
    }

    protected void installApk(File file) {
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //data和type数据是会相互覆盖的
        /*intent.setData(Uri.fromFile(new File(SAVEAPKURL)));
        intent.setType("application/vnd.android.package-archive");*/
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            //当当前的界面退出的时候，会调用之前activity的onActivityResult方法
            //startActivityForResult(intent, 0);
            startActivity(intent);
        }else{//高于6.0，必须用下面的方法
            try {
                openFile(file);
            } catch (Exception e) {
                e.printStackTrace();
                showToast("没有找到打开此类文件的程序");
            }
        }
    }

    private void openFile(File file) throws Exception{
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        //7.0
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
            Uri uriForFile = FileProvider.getUriForFile(this,
                    getApplicationContext().getPackageName() + ".provider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uriForFile, getContentResolver().getType(uriForFile));
        }else{
            intent.setDataAndType(Uri.fromFile(file), getMIMEType(file));
        }
        startActivity(intent);
    }



    private String getMIMEType(File file) {
        String var1 = "";
        String var2 = file.getName();
        String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
        return var1;
    }
}
